package com.xy.blog.user.dao.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xy.blog.core.dao.IBaseCommonDao;
import com.xy.blog.core.exception.BaseException;
import com.xy.blog.core.id.SnowflakeIdWorker;
import com.xy.blog.core.springmvc.result.page.PageReq;
import com.xy.blog.core.springmvc.result.page.PageResp;
import com.xy.blog.user.controller.model.req.query.SysDictQuery;
import com.xy.blog.user.dao.ISysDictDao;
import com.xy.blog.user.dao.mapper.SysDictMapper;
import com.xy.blog.user.dao.model.SysDictDO;
import com.xy.blog.user.exception.constants.SysDictErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zanhonglei
 * @version V1.0
 * @Description: 数据字段
 * @date 2020/3/5
 */
@Repository
public class SysDictDaoImpl implements IBaseCommonDao<SysDictDO, SysDictQuery>, ISysDictDao {

    @Autowired
    private SysDictMapper sysDictMapper;

    @Override
    public PageResp<SysDictDO> listByPage(PageReq<SysDictQuery> req) {
        Page<Object> objects = PageHelper.startPage(req);
        List<SysDictDO> sysDictDOS = sysDictMapper.selectAll();
        return PageResp.data(sysDictDOS);
    }

    @Override
    public List<SysDictDO> select(SysDictDO item) {
        return sysDictMapper.select(item);
    }

    @Override
    public int selectCount(SysDictDO item) {
        return 0;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void save(SysDictDO item) throws BaseException {
        if (item.getId() == null) {
            item.setId(SnowflakeIdWorker.generateId());
        }
        SysDictDO sysDictQuery = new SysDictDO();
        sysDictQuery.setSKey(item.getSKey());
        if (sysDictMapper.selectCount(sysDictQuery) > 0) {
            throw new BaseException(SysDictErrorCode.KEY_EXITS);
        }
        sysDictMapper.insert(item);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateById(SysDictDO item) {
        SysDictDO sysDictQuery = new SysDictDO();
        sysDictQuery.setSKey(item.getSKey());
        if (sysDictMapper.selectCount(sysDictQuery) > 0) {
            throw new BaseException(SysDictErrorCode.KEY_EXITS);
        }
        sysDictMapper.updateByPrimaryKeySelective(item);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void deleteById(Long id) {
        sysDictMapper.deleteByPrimaryKey(id);
    }

    @Override
    public SysDictDO getById(Long id) {
        return sysDictMapper.selectByPrimaryKey(id);
    }
}
